<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>React Router原理 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="React,Javascript,">
  

  <meta name="description" content="一、React Router基础之history1.1 History介绍 history是一个独立的第三方js库，可以用来兼容在不同浏览器、不同环境下对历史记录的管理，拥有统一的API。具体来说里面的history分为三类   老浏览器的history: 主要通过hash来实现，对应createHashHistory 高版本浏览器: 通过html5里面的history，对应createBrows">
<meta name="keywords" content="React,Javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="React Router原理">
<meta property="og:url" content="http://blog.poetries.top/2018/12/20/react-router-anaylse/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、React Router基础之history1.1 History介绍 history是一个独立的第三方js库，可以用来兼容在不同浏览器、不同环境下对历史记录的管理，拥有统一的API。具体来说里面的history分为三类   老浏览器的history: 主要通过hash来实现，对应createHashHistory 高版本浏览器: 通过html5里面的history，对应createBrows">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/7/11/164888109d57995f?w=942&h=493&f=png&s=39581">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/7/11/164888478584a217?w=1244&h=585&f=png&s=59637">
<meta property="og:image" content="http://zhenhua-lee.github.io/img/react-router/base.png">
<meta property="og:image" content="http://zhenhua-lee.github.io/img/react-router/base.png">
<meta property="og:image" content="http://zhenhua-lee.github.io/img/react-router/internal.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/429.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/430.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React Router原理">
<meta name="twitter:description" content="一、React Router基础之history1.1 History介绍 history是一个独立的第三方js库，可以用来兼容在不同浏览器、不同环境下对历史记录的管理，拥有统一的API。具体来说里面的history分为三类   老浏览器的history: 主要通过hash来实现，对应createHashHistory 高版本浏览器: 通过html5里面的history，对应createBrows">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/7/11/164888109d57995f?w=942&h=493&f=png&s=39581">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、React-Router基础之history"><span class="toc-text">一、React Router基础之history</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-History介绍"><span class="toc-text">1.1 History介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-内部解析"><span class="toc-text">1.2 内部解析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-1-执行URL前进"><span class="toc-text">1.2.1 执行URL前进</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-2-检测URL回退"><span class="toc-text">1.2.2 检测URL回退</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-3-state的存储"><span class="toc-text">1.2.3 state的存储</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-小结"><span class="toc-text">1.3 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、react-router的基本原理"><span class="toc-text">二、react-router的基本原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-优点"><span class="toc-text">2.1 优点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-react-router具体实现"><span class="toc-text">2.2 react-router具体实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-用户点击了Link组件后路由系统中到底发生了哪些变化"><span class="toc-text">2.3 用户点击了Link组件后路由系统中到底发生了哪些变化</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-react-router-anaylse" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">React Router原理</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.12.20</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、React-Router基础之history"><a href="#一、React-Router基础之history" class="headerlink" title="一、React Router基础之history"></a>一、React Router基础之history</h2><h3 id="1-1-History介绍"><a href="#1-1-History介绍" class="headerlink" title="1.1 History介绍"></a>1.1 History介绍</h3><blockquote>
<p><code>history</code>是一个独立的第三方js库，可以用来兼容在不同浏览器、不同环境下对历史记录的管理，拥有统一的<code>API</code>。具体来说里面的<code>history</code>分为三类</p>
</blockquote>
<ul>
<li>老浏览器的<code>history</code>: 主要通过<code>hash</code>来实现，对应<code>createHashHistory</code></li>
<li>高版本浏览器: 通过<code>html5</code>里面的<code>history</code>，对应<code>createBrowserHistory</code></li>
<li><code>node</code>环境下: 主要存储在<code>memeory</code>里面，对应<code>createMemoryHistory</code></li>
</ul>
<blockquote>
<p>上面针对不同的环境提供了三个<code>API</code>，但是三个<code>API</code>有一些共性的操作，将其抽象了一个公共的文件<code>createHistory</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 内部的抽象实现</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createHistory</span>(<span class="params">options=&#123;&#125;</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    listenBefore, <span class="comment">// 内部的hook机制，可以在location发生变化前执行某些行为，AOP的实现</span></span><br><span class="line">    listen, <span class="comment">// location发生改变时触发回调</span></span><br><span class="line">    transitionTo, <span class="comment">// 执行location的改变</span></span><br><span class="line">    push, <span class="comment">// 改变location</span></span><br><span class="line">    replace,</span><br><span class="line">    go,</span><br><span class="line">    goBack,</span><br><span class="line">    goForward,</span><br><span class="line">    createKey, <span class="comment">// 创建location的key，用于唯一标示该location，是随机生成的</span></span><br><span class="line">    createPath,</span><br><span class="line">    createHref,</span><br><span class="line">    createLocation, <span class="comment">// 创建location</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上述这些方式是<code>history</code>内部最基础的方法，<code>createHashHistory</code>、<code>createBrowserHistory</code>、<code>createMemoryHistory</code>只是覆盖其中的某些方法而已。其中需要注意的是，此时的<code>location</code>跟浏览器原生的<code>location</code>是不相同的，最大的区别就在于里面多了<code>key</code>字段，<code>history</code>内部通过<code>key</code>来进行<code>location</code>的操作</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createLocation</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    pathname, <span class="comment">// url的基本路径</span></span><br><span class="line">    search, <span class="comment">// 查询字段</span></span><br><span class="line">    hash, <span class="comment">// url中的hash值</span></span><br><span class="line">    state, <span class="comment">// url对应的state字段</span></span><br><span class="line">    action, <span class="comment">// 分为 push、replace、pop三种</span></span><br><span class="line">    key <span class="comment">// 生成方法为: Math.random().toString(36).substr(2, length)</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-2-内部解析"><a href="#1-2-内部解析" class="headerlink" title="1.2 内部解析"></a>1.2 内部解析</h3><blockquote>
<p>三个<code>API</code>的大致的技术实现如下</p>
</blockquote>
<ul>
<li><code>createBrowserHistory</code>: 利用<code>HTML5</code>里面的<code>history</code></li>
<li><code>createHashHistory</code>: 通过<code>hash</code>来存储在不同状态下的<code>history</code>信息</li>
<li><code>createMemoryHistory</code>: 在内存中进行历史记录的存储`</li>
</ul>
<h4 id="1-2-1-执行URL前进"><a href="#1-2-1-执行URL前进" class="headerlink" title="1.2.1 执行URL前进"></a>1.2.1 执行URL前进</h4><ul>
<li><code>createBrowserHistory</code>: <code>pushState</code>、<code>replaceState</code></li>
<li><code>createHashHistory</code>: <code>location.hash=*** location.replace()</code></li>
<li><code>createMemoryHistory</code>: 在内存中进行历史记录的存储</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 伪代码</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// createBrowserHistory(HTML5)中的前进实现</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">finishTransition</span>(<span class="params">location</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">const</span> historyState = &#123; key &#125;;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">if</span> (location.action === <span class="string">'PUSH'</span>) ) &#123;</span><br><span class="line">    <span class="built_in">window</span>.history.pushState(historyState, <span class="literal">null</span>, path);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">window</span>.history.replaceState(historyState, <span class="literal">null</span>, path)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// createHashHistory的内部实现</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">finishTransition</span>(<span class="params">location</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">if</span> (location.action === <span class="string">'PUSH'</span>) ) &#123;</span><br><span class="line">    <span class="built_in">window</span>.location.hash = path;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">window</span>.location.replace(</span><br><span class="line">    <span class="built_in">window</span>.location.pathname + <span class="built_in">window</span>.location.search + <span class="string">'#'</span> + path</span><br><span class="line">  );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// createMemoryHistory的内部实现</span></span><br><span class="line">entries = [];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">finishTransition</span>(<span class="params">location</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">switch</span> (location.action) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'PUSH'</span>:</span><br><span class="line">      entries.push(location);</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'REPLACE'</span>:</span><br><span class="line">      entries[current] = location;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="1-2-2-检测URL回退"><a href="#1-2-2-检测URL回退" class="headerlink" title="1.2.2 检测URL回退"></a>1.2.2 检测URL回退</h4><ul>
<li><code>createBrowserHistory</code>: <code>popstate</code></li>
<li><code>createHashHistory</code>: <code>hashchange</code></li>
<li><code>createMemoryHistory</code>:因为是在内存中操作，跟浏览器没有关系，不涉及<code>UI</code>层面的事情，所以可以直接进行历史信息的回退</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 伪代码</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// createBrowserHistory(HTML5)中的后退检测</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">startPopStateListener</span>(<span class="params">&#123; transitionTo &#125;</span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">popStateListener</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    transitionTo( getCurrentLocation(event.state) );</span><br><span class="line">  &#125;</span><br><span class="line">  addEventListener(<span class="built_in">window</span>, <span class="string">'popstate'</span>, popStateListener);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// createHashHistory的后退检测</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">startPopStateListener</span>(<span class="params">&#123; transitionTo &#125;</span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">hashChangeListener</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    transitionTo( getCurrentLocation(event.state) );</span><br><span class="line">  &#125;</span><br><span class="line">  addEventListener(<span class="built_in">window</span>, <span class="string">'hashchange'</span>, hashChangeListener);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// createMemoryHistory的内部实现</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">go</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (n) &#123;</span><br><span class="line">    ...</span><br><span class="line">    current += n;</span><br><span class="line">  <span class="keyword">const</span> currentLocation = getCurrentLocation();</span><br><span class="line">  <span class="comment">// change action to POP</span></span><br><span class="line">  history.transitionTo(&#123; ...currentLocation, <span class="attr">action</span>: POP &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="1-2-3-state的存储"><a href="#1-2-3-state的存储" class="headerlink" title="1.2.3 state的存储"></a>1.2.3 state的存储</h4><blockquote>
<p>为了维护<code>state</code>的状态，将其存储在<code>sessionStorage</code>里面:</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// createBrowserHistory/createHashHistory中state的存储</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">saveState</span>(<span class="params">key, state</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="built_in">window</span>.sessionStorage.setItem(createKey(key), <span class="built_in">JSON</span>.stringify(state));</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">readState</span>(<span class="params">key</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  json = <span class="built_in">window</span>.sessionStorage.getItem(createKey(key));</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">JSON</span>.parse(json);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// createMemoryHistory仅仅在内存中，所以操作比较简单</span></span><br><span class="line"><span class="keyword">const</span> storage = createStateStorage(entries); <span class="comment">// storage = &#123;entry.key: entry.state&#125;</span></span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">saveState</span>(<span class="params">key, state</span>) </span>&#123;</span><br><span class="line">  storage[key] = state</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">readState</span>(<span class="params">key</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> storage[key]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-3-小结"><a href="#1-3-小结" class="headerlink" title="1.3 小结"></a>1.3 小结</h3><p><strong>路由原理</strong></p>
<blockquote>
<p>前端路由实现起来其实很简单，本质就是监听 <code>URL</code> 的变化，然后匹配路由规则，显示相应的页面，并且无须刷新。目前单页面使用的路由就只有两种实现方式</p>
</blockquote>
<ul>
<li><code>hash</code> 模式</li>
<li><code>history</code> 模式</li>
</ul>
<blockquote>
<p><code>www.test.com/##/</code> 就是 <code>Hash URL</code>，当 <code>##</code> 后面的哈希值发生变化时，不会向服务器请求数据，可以通过 <code>hashchange</code> 事件来监听到 <code>URL</code> 的变化，从而进行跳转页面。</p>
</blockquote>
<p><img src="https://user-gold-cdn.xitu.io/2018/7/11/164888109d57995f?w=942&amp;h=493&amp;f=png&amp;s=39581" alt></p>
<blockquote>
<p><code>History</code>模式是 <code>HTML5</code>新推出的功能，比之 <code>Hash URL</code> 更加美观</p>
</blockquote>
<p><img src="https://user-gold-cdn.xitu.io/2018/7/11/164888478584a217?w=1244&amp;h=585&amp;f=png&amp;s=59637" alt></p>
<h2 id="二、react-router的基本原理"><a href="#二、react-router的基本原理" class="headerlink" title="二、react-router的基本原理"></a>二、react-router的基本原理</h2><blockquote>
<p>实现<code>URL</code>与<code>UI</code>界面的同步。其中在<code>react-router</code>中，<code>URL</code>对应<code>Location</code>对象，而<code>UI</code>是由<code>react components</code>来决定的，这样就转变成<code>location</code>与<code>components</code>之间的同步问题</p>
</blockquote>
<p><img src="http://zhenhua-lee.github.io/img/react-router/base.png" alt></p>
<h3 id="2-1-优点"><a href="#2-1-优点" class="headerlink" title="2.1 优点"></a>2.1 优点</h3><ul>
<li>与<code>React</code>融为一体,专为<code>react</code>量身打造，编码风格与<code>react</code>保持一致，例如路由的配置可以通过<code>component</code>来实现</li>
<li>不需要手工维护路由<code>state</code>，使代码变得简单</li>
<li>强大的路由管理机制，体现在如下方面<ul>
<li>路由配置: 可以通过组件、配置对象来进行路由的配置</li>
<li>路由切换: 可以通过<code>&lt;Link&gt;</code> <code>Redirect</code>进行路由的切换</li>
<li>路由加载: 可以同步记载，也可以异步加载，这样就可以实现按需加载</li>
</ul>
</li>
<li>使用方式: 不仅可以在浏览器端的使用，而且可以在服务器端的使用</li>
</ul>
<h3 id="2-2-react-router具体实现"><a href="#2-2-react-router具体实现" class="headerlink" title="2.2 react-router具体实现"></a>2.2 react-router具体实现</h3><blockquote>
<p><code>react-router</code>在<code>history</code>库的基础上，实现了<code>URL</code>与<code>UI</code>的同步，分为两个层次来描述具体的实现。</p>
</blockquote>
<p><strong>组件层面描述实现过程</strong></p>
<blockquote>
<p>在<code>react-router</code>中最主要的<code>component</code>是<code>Router RouterContext Link</code>，<code>history</code>库起到了中间桥梁的作用</p>
</blockquote>
<p><img src="http://zhenhua-lee.github.io/img/react-router/base.png" alt></p>
<blockquote>
<p>以<code>browserHistory</code>(一种<code>history</code>类型:一个 <code>history</code> 知道如何去监听浏览器地址栏的变化， 并解析这个 <code>URL</code> 转化为 <code>location</code> 对象)为例 :</p>
</blockquote>
<ul>
<li><code>browserHistory</code>进行路由<code>state</code>管理,主要通过<code>sessionStorage</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//保存　路由state(router state)</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">saveState</span>(<span class="params">key, state</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="built_in">window</span>.sessionStorage.setItem(createKey(key), <span class="built_in">JSON</span>.stringify(state));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//读取路由state</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">readState</span>(<span class="params">key</span>) </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  json = <span class="built_in">window</span>.sessionStorage.getItem(createKey(key));</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">JSON</span>.parse(json);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>其中<code>saveState</code>函数传进来的<code>state</code>是个<code>json</code>对象，如：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&#123;<span class="attr">route</span>: <span class="string">'/about'</span>&#125; <span class="comment">///假设此时的location为'/about'</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>进行路由匹配，最终渲染对应的组件</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> About = React.createClass(&#123;<span class="comment">/*...*/</span>&#125;) <span class="comment">//About 组件</span></span><br><span class="line"><span class="keyword">const</span> Inbox = React.createClass(&#123;<span class="comment">/*...*/</span>&#125;) <span class="comment">//Inbox 组件</span></span><br><span class="line"><span class="keyword">const</span> Home = React.createClass(&#123;<span class="comment">/*...*/</span>&#125;) <span class="comment">//Home组件</span></span><br><span class="line"> render() &#123;</span><br><span class="line">    <span class="keyword">let</span> Child</span><br><span class="line">    <span class="keyword">switch</span> (<span class="keyword">this</span>.state.route) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'/about'</span>: Child = About; <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'/inbox'</span>: Child = Inbox; <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>:      Child = Home;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;h1&gt;App&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">        &lt;ul&gt;</span></span><br><span class="line"><span class="regexp">          &lt;li&gt;&lt;a href="#/</span>about<span class="string">"&gt;About&lt;/a&gt;&lt;/li&gt;</span></span><br><span class="line">          &lt;li&gt;&lt;a href="#/inbox"&gt;Inbox&lt;/a&gt;&lt;/li&gt;</span><br><span class="line">        &lt;<span class="regexp">/ul&gt;</span></span><br><span class="line"><span class="regexp">        &lt;Child/</span>&gt;</span><br><span class="line">      &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;)</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">React.render(&lt;App /</span>&gt;, <span class="built_in">document</span>.body)</span><br></pre></td></tr></table></figure>
<p><strong>API层面描述实现过程</strong></p>
<blockquote>
<p>为了简单说明，只描述使用<code>browserHistory</code>的实现，<code>hashHistory</code>的实现过程是类似的，就不在说明</p>
</blockquote>
<p><img src="http://zhenhua-lee.github.io/img/react-router/internal.png" alt></p>
<h3 id="2-3-用户点击了Link组件后路由系统中到底发生了哪些变化"><a href="#2-3-用户点击了Link组件后路由系统中到底发生了哪些变化" class="headerlink" title="2.3 用户点击了Link组件后路由系统中到底发生了哪些变化"></a>2.3 用户点击了Link组件后路由系统中到底发生了哪些变化</h3><p><img src="https://poetries1.gitee.io/img-repo/2019/10/429.png" alt></p>
<blockquote>
<p><code>Link</code> 组件最终会渲染为 <code>HTML</code> 标签 <code>&lt;a&gt;</code>，它的 <code>to</code>、<code>query</code>、<code>hash</code>属性会被组合在一起并渲染为 <code>href</code> 属性。虽然 <code>Link</code> 被渲染为超链接，但在内部实现上使用脚本拦截了浏览器的默认行为，然后调用了<code>history.pushState</code> 方法</p>
</blockquote>
<ul>
<li>系统会将上述 <code>location</code>对象作为参数传入到 <code>TransitionTo</code>方法中，然后调用 <code>window.location.hash</code> 或者<code>window.history.pushState()</code> 修改了应用的 <code>URL</code>，这取决于你创建<code>history</code>对象的方式。同时会触发<code>history.listen</code> 中注册的事件监听器。</li>
<li>接下来请看路由系统内部是如何修改<code>UI</code> 的。在得到了新的<code>location</code>对象后，系统内部的 <code>matchRoutes</code> 方法会匹配出<code>Route</code> 组件树中与当前<code>location</code>对象匹配的一个子集，并且得到了 <code>nextState</code>，具体的匹配算法不在这里讲解，感兴趣的同学可以点击查看，<code>state</code> 的结构如下</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">nextState = &#123;</span><br><span class="line">  location, <span class="comment">// 当前的 location 对象</span></span><br><span class="line">  routes, <span class="comment">// 与 location 对象匹配的 Route 树的子集，是一个数组</span></span><br><span class="line">  params, <span class="comment">// 传入的 param，即 URL 中的参数</span></span><br><span class="line">  components, <span class="comment">// routes 中每个元素对应的组件，同样是数组</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在 <code>Router</code> 组件的 <code>componentWillMount</code> 生命周期方法中调用了 <code>history.listen(listener)</code> 方法。<code>listener</code> 会在上述 <code>matchRoutes</code> 方法执行成功后执行<code>listener(nextState)</code>，<code>nextState</code>对象每个属性的具体含义已经在上述代码中注释，接下来执行<code>this.setState(nextState)</code> 就可以实现重新渲染 <code>Router</code>组件。举个简单的例子，当 URL（准确的说应该是 <code>location.pathname</code>） 为 <code>/archives/posts</code> 时，应用的匹配结果如下图所示</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/430.png" alt></p>
<blockquote>
<p>到这里，系统已经完成了当用户点击一个由 <code>Link</code> 组件渲染出的超链接到页面刷新的全过程</p>
</blockquote>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/12/20/quickapp-oppo-openid/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/12/20/promise-anaylse/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
